package com.lefevre.cms.web.action.theme;

import com.lefevre.cms.bean.theme.Themes;
import com.lefevre.cms.service.theme.ThemeService;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import javax.annotation.Resource;

/**
 * 模板校验器
 */
@Component("templateValidator")
public class TemplateValidator implements Validator {

    @Resource(name = "themeServiceImpl")
    private ThemeService themeService;


    @Override
    public boolean supports(Class<?> clazz) {//该校验器支持的目标类
        return clazz.equals(Themes.class);
    }

    @Override
    public void validate(Object obj, Errors errors) {//对目标类对象进行校验，错误记录在errors中
        Themes themes = (Themes) obj;

        if (themes.getName() == null || "".equals(themes.getName().trim())) {
            errors.rejectValue("name", "errors.required", new String[]{"模板名称不能为空"}, "");
        } else {
            if (themes.getName().length() > 80) {
                errors.rejectValue("name", "errors.required", new String[]{"模板名称过长"}, "");
            }
        }
        if (themes.getDirName() == null || "".equals(themes.getDirName().trim())) {
            errors.rejectValue("dirName", "errors.required", new String[]{"模板目录不能为空"}, "");
        } else {
            if (themes.getDirName().length() > 40) {
                errors.rejectValue("dirName", "errors.required", new String[]{"目录名称过长"}, "");
            } else {
                //只能输入字母或下划线
                if (!themes.getDirName().matches("^[a-zA-Z][a-zA-Z0-9|_]{2,40}$")) {
                    errors.rejectValue("dirName", "errors.required", new String[]{"只能由字母或数字或下划线组成,并且开头为字母，总长度大于两个字符"}, "");
                } else {
                    //验证目录是否重复
                    Themes t = themeService.findTemplateByDirName(themes.getDirName().trim());
                    if (t != null) {
                        errors.rejectValue("dirName", "errors.required", new String[]{"模板目录不能重复"}, "");
                    }
                }
            }


        }

    }
}
